﻿using System.Text;

using RabbitMQ.Client;
using RabbitMQ.Client.Events;

using RabbitMQSample.WebApi.RabbitMQLibs;

namespace RabbitMQSample.WebApi.Samples
{
    public class RabbitMQShareConsumerSample : RabbitMQShareConsumerBase
    {
        public RabbitMQShareConsumerSample(IRabbitMQConnectionFactory rabbitMQConnectionFactory, ILogger<RabbitMQShareConsumerSample> logger) : base(rabbitMQConnectionFactory, logger)
        {
        }

        protected override string QueueName => "demo_queue";

        protected override ushort PrefetchCount => 50;

        protected override string ExchangeName => "demo_exchange";
        protected override string ExchangeType => RabbitMQ.Client.ExchangeType.Direct;
        protected override string RoutingKey => "demo_routing_key";

        //protected override bool HandlerMessage(BasicDeliverEventArgs e)
        //{
        //    try
        //    {
        //        string message = Encoding.UTF8.GetString(e.Body.Span);
        //        _logger.LogInformation(message);
        //    }
        //    catch (Exception ex)
        //    {
        //        _logger.LogError($"{nameof(HandlerMessage)} 报错记录:{ex.StackTrace},{ex.Message}");
        //    }

        //    return true;
        //}

        protected async override Task<bool> HandlerMessage(BasicDeliverEventArgs e)
        {
            try
            {
                string message = Encoding.UTF8.GetString(e.Body.Span);
                _logger.LogInformation($"消费消息：{message}");
            }
            catch (Exception ex)
            {
                _logger.LogError($"{nameof(HandlerMessage)} 报错记录:{ex.StackTrace},{ex.Message}");
                return await Task.FromResult(false);
            }

            return await Task.FromResult(true);
        }
    }
}
